package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.Constants;
import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.mapper.ElderMapper;
import com.zzyl.service.BedService;
import com.zzyl.vo.BedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.zzyl.base.ResponseResult.error;
import static com.zzyl.base.ResponseResult.success;

@Service
public class BedServiceImpl implements BedService {

    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ElderMapper elderMapper;

    /**
     * 通过房间ID检索床位
     * @param roomId 房间ID
     * @return 床位视图对象列表
     */
    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }


    /**
     * 新增床位
     * @param bedDto
     */
    @Override
    public void addBed(BedDto bedDto) {
        //1.把dto转成bed对象
        Bed bed = BeanUtil.toBean(bedDto,Bed.class);
        //2.设置空闲状态，写成常量
        bed.setBedStatus(Constants.BED_STATUS_NOTUSE);
        //3.修改和创建时间
//        拦截器自动注册
//        bed.setCreateTime(LocalDateTime.now());

      //创建者，当前登录用户 //TODO 第九天补上
        bed.setCreateBy(1L);

        bedMapper.addBed(bed);
    }

    /**
     * 根据id查询床位信息
     * @param id
     * @return BedVo
     */
    @Override
    public BedVo getById(Long id) {

        //查询床位
        Bed bed = bedMapper.getById(id);
        BedVo bedVo = BeanUtil.toBean(bed, BedVo.class);//BeanUtil.copyProperties(bed,BedVo.class);
        return bedVo;
    }

    /**
     * 更新床位信息
     * @param bedDto
     */
    @Override
    public void updateBed(BedDto bedDto) {
        //更新修改时间，修改人
        Bed bed = BeanUtil.toBean(bedDto, Bed.class);
        bed.setUpdateBy(1L);
        bed.setUpdateTime(LocalDateTime.now());
        bedMapper.updateBed(bed);

    }

    /**
     *根据id删除床位，要判断当前床位有没有老人入住
     * @param id
     */
    @Override
    public ResponseResult deleteById(Long id) {
        //获取老人的入住状态，234就不能删除
        Long status = elderMapper.getByBedId(id);
        if (  status == null ||(status == 0  || status == 5) ){
            bedMapper.deleteByBedId(id);
           return success("成功");
        }else {
            throw new BaseException(BasicEnum.BED_DELETE_FAIL);
        }

    }

}                                                                                                                                              

